{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Haz6F_gnRjlS"
      },
      "outputs": [],
      "source": [
        "!pip install --upgrade --quiet  google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client langchain langchain-community langchain-openai langchainhub"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Create the Gmail Toolkit from LangChain"
      ],
      "metadata": {
        "id": "xKUdDGbbq1_Z"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from langchain_community.agent_toolkits import GmailToolkit\n",
        "from langchain_community.tools.gmail.utils import (\n",
        "    build_resource_service,\n",
        "    get_gmail_credentials,\n",
        ")\n",
        "\n",
        "\n",
        "credentials = get_gmail_credentials(\n",
        "    scopes=[\"https://www.googleapis.com/auth/gmail.readonly\"],\n",
        "    client_secrets_file=\"/content/web_credentials.json\",\n",
        "    token_file = \"/content/token.json\"\n",
        ")\n",
        "\n",
        "print(\"credentials Generated....\")\n",
        "api_resource = build_resource_service(credentials=credentials)\n",
        "toolkit = GmailToolkit(api_resource=api_resource)"
      ],
      "metadata": {
        "id": "Nf4ovfrvBCai",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "1cc5f4fd-6a79-47e2-9f97-eea1daa8e316"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "credentials Generated....\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "tools = toolkit.get_tools()\n",
        "tools"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "Y8d0GUffCawH",
        "outputId": "19fc2a8e-fcac-4f4f-f236-af4ec09644b0"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[GmailCreateDraft(api_resource=<googleapiclient.discovery.Resource object at 0x7878d7c935e0>),\n",
              " GmailSendMessage(api_resource=<googleapiclient.discovery.Resource object at 0x7878d7c935e0>),\n",
              " GmailSearch(api_resource=<googleapiclient.discovery.Resource object at 0x7878d7c935e0>),\n",
              " GmailGetMessage(api_resource=<googleapiclient.discovery.Resource object at 0x7878d7c935e0>),\n",
              " GmailGetThread(api_resource=<googleapiclient.discovery.Resource object at 0x7878d7c935e0>)]"
            ]
          },
          "metadata": {},
          "execution_count": 3
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Passing your Openai API Key"
      ],
      "metadata": {
        "id": "l6j47L7Jq_gl"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import getpass\n",
        "import os\n",
        "\n",
        "os.environ[\"OPENAI_API_KEY\"] = getpass.getpass()"
      ],
      "metadata": {
        "id": "bUWQ-oRpDTgs",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "0978dbd7-9fab-41c3-e25f-b7239d13d3dc"
      },
      "execution_count": null,
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "··········\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Working with Gmails with OpenAI Tools Agent"
      ],
      "metadata": {
        "id": "hs5ZJwWqrKBx"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from langchain import hub\n",
        "from langchain.agents import AgentExecutor, create_openai_tools_agent\n",
        "from langchain_openai import ChatOpenAI"
      ],
      "metadata": {
        "id": "BRn0Fp2bDxnq"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "instructions = \"\"\"You are an assistant.\"\"\"\n",
        "base_prompt = hub.pull(\"langchain-ai/openai-functions-template\")\n",
        "prompt = base_prompt.partial(instructions=instructions)"
      ],
      "metadata": {
        "id": "B5tX0DVxD07g"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "prompt"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "phl7vbXd7965",
        "outputId": "3fd07d2f-fd7f-47d2-bfb3-6bff81574312"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "ChatPromptTemplate(input_variables=['agent_scratchpad', 'input'], input_types={'chat_history': typing.List[typing.Union[langchain_core.messages.ai.AIMessage, langchain_core.messages.human.HumanMessage, langchain_core.messages.chat.ChatMessage, langchain_core.messages.system.SystemMessage, langchain_core.messages.function.FunctionMessage, langchain_core.messages.tool.ToolMessage]], 'agent_scratchpad': typing.List[typing.Union[langchain_core.messages.ai.AIMessage, langchain_core.messages.human.HumanMessage, langchain_core.messages.chat.ChatMessage, langchain_core.messages.system.SystemMessage, langchain_core.messages.function.FunctionMessage, langchain_core.messages.tool.ToolMessage]]}, partial_variables={'instructions': 'You are an assistant.'}, metadata={'lc_hub_owner': 'langchain-ai', 'lc_hub_repo': 'openai-functions-template', 'lc_hub_commit_hash': 'b4198088b0f11cbe911a9e1cb6546893c00283b6cf0f80ae003b3955efdfe281'}, messages=[SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=['instructions'], template='{instructions}')), MessagesPlaceholder(variable_name='chat_history', optional=True), HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['input'], template='{input}')), MessagesPlaceholder(variable_name='agent_scratchpad')])"
            ]
          },
          "metadata": {},
          "execution_count": 6
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "llm = ChatOpenAI(temperature=0)"
      ],
      "metadata": {
        "id": "0EOomk4ED_L9"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "agent = create_openai_tools_agent(llm, toolkit.get_tools(), prompt)"
      ],
      "metadata": {
        "id": "EFxek3tLD6-8"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "agent_executor = AgentExecutor(\n",
        "    agent=agent,\n",
        "    tools=toolkit.get_tools(),\n",
        "    # This is set to False to prevent information about my email showing up on the screen\n",
        "    # Normally, it is helpful to have it set to True however.\n",
        "    verbose=True,\n",
        ")"
      ],
      "metadata": {
        "id": "OxVDBrHaEBd0"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "agent_executor.invoke(\n",
        "    {\n",
        "        \"input\": \"Create a gmail draft for me to reschedule my meeting from sunday to morning to monday morning\"\n",
        "        \" as I will be not available because of a football match. The recipient is rounak.1210@gmail.com\"\n",
        "        \" keep the tone of the email polite\"\n",
        "    }\n",
        ")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "FNIyQnBdEIqI",
        "outputId": "b8bb6498-df3a-4cf3-f111-ecee62d48640"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "\n",
            "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
            "\u001b[32;1m\u001b[1;3m\n",
            "Invoking: `create_gmail_draft` with `{'message': 'Dear Rounak, \\n\\nI hope this message finds you well. I wanted to inform you that I have a prior commitment on Sunday morning and will not be available for our meeting. Would it be possible to reschedule our meeting to Monday morning instead? I apologize for any inconvenience this may cause. Thank you for your understanding. \\n\\nBest regards, [Your Name]', 'to': ['rounak.1210@gmail.com'], 'subject': 'Meeting Rescheduling Request'}`\n",
            "\n",
            "\n",
            "\u001b[0m\u001b[36;1m\u001b[1;3mDraft created. Draft Id: r-922369640620305716\u001b[0m\u001b[32;1m\u001b[1;3mI have created a draft email for you to reschedule your meeting from Sunday morning to Monday morning. The draft has been saved, and you can review and send it from your Gmail account.\u001b[0m\n",
            "\n",
            "\u001b[1m> Finished chain.\u001b[0m\n"
          ]
        },
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "{'input': 'Create a gmail draft for me to reschedule my meeting from sunday to morning to monday morning as I will be not available because of a football match. The recipient is rounak.1210@gmail.com keep the tone of the email polite',\n",
              " 'output': 'I have created a draft email for you to reschedule your meeting from Sunday morning to Monday morning. The draft has been saved, and you can review and send it from your Gmail account.'}"
            ]
          },
          "metadata": {},
          "execution_count": 12
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "agent_executor.invoke(\n",
        "    {\"input\": \"Could you search in primary inbox for the latest email? what is the title?\"}\n",
        ")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "0fZ0KmYmEgaT",
        "outputId": "cb694274-0354-4ab7-e7c3-eae42e7a8a1e"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "\n",
            "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
            "\u001b[32;1m\u001b[1;3m\n",
            "Invoking: `search_gmail` with `{'query': 'label:inbox category:primary', 'max_results': 1}`\n",
            "\n",
            "\n",
            "\u001b[0m\u001b[38;5;200m\u001b[1;3m[{'id': '18e609ee4cb6fb88', 'threadId': '18e609ee4cb6fb88', 'snippet': '[11/25/2023, 12:06] Rik: Developed a Python-based NLP tool using Google API and BERT for sentiment analysis of YouTube video comments. I scraped comments from YouTube video URLs, conducted contextual', 'body': '[11/25/2023, 12:06] Rik: Developed a Python-based NLP tool using Google API\\r\\nand BERT for sentiment analysis of YouTube video comments. I scraped\\r\\ncomments from YouTube video URLs, conducted contextual sentiment analysis,\\r\\nand predicted sentiment as star ratings (1-5).\\r\\n[11/25/2023, 12:08] Rik: Moreover, my News QnA Analyzer Tool project\\r\\ninvolved implementing advanced NLP techniques. I developed and implemented\\r\\nan automated content analysis tool that processed URLs of news articles,\\r\\ndelivering comprehensive answers to user-generated\\r\\nquestions; reduced research time by 50% and improved content accuracy by\\r\\n20%. I utilize Langchain and LLM to automatically analyze news articles and\\r\\nprovide detailed answers to user-generated questions related to the content.\\r\\n', 'subject': 'Sample msg', 'sender': 'Rounak show <rounak.1210@gmail.com>'}]\u001b[0m\u001b[32;1m\u001b[1;3mThe latest email in your primary inbox has the title \"Sample msg\".\u001b[0m\n",
            "\n",
            "\u001b[1m> Finished chain.\u001b[0m\n"
          ]
        },
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "{'input': 'Could you search in primary inbox for the latest email? what is the title?',\n",
              " 'output': 'The latest email in your primary inbox has the title \"Sample msg\".'}"
            ]
          },
          "metadata": {},
          "execution_count": 27
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Pass Custom Prompt"
      ],
      "metadata": {
        "id": "QpZzG7j7rlHG"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
        "\n",
        "prompt = ChatPromptTemplate.from_messages(\n",
        "    [\n",
        "        (\"system\", \"\"\"\n",
        "You are a helpful assistant.\n",
        "\"\"\"),\n",
        "        MessagesPlaceholder(\"chat_history\", optional=True),\n",
        "        (\"human\", \"{input}\"),\n",
        "        MessagesPlaceholder(\"agent_scratchpad\"),\n",
        "    ]\n",
        ")\n",
        "\n",
        "agent = create_openai_tools_agent(llm, tools, prompt)\n",
        "agent_executor = AgentExecutor(\n",
        "        agent=agent,\n",
        "        tools=tools,\n",
        "        verbose=True,\n",
        "        return_intermediate_steps=True\n",
        "    )\n",
        "\n",
        "response = agent_executor.invoke(\n",
        "                    {\n",
        "                        \"input\": user_query,\n",
        "                        \"chat_history\": chat_history,\n",
        "                    }\n",
        "    )\n"
      ],
      "metadata": {
        "id": "jM-37mFdyjpj"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}